<?php
namespace app\admin\controller;
use think\Controller;
use app\admin\model\User as UserModel;
use think\Request;
use think\Db;
use think\Session;
use sms\rong\Rest;
use mail\Smtp;

class Index extends Base
{
    // 展示数据
    public function index()
    {
        return $this->fetch();
    }

    // 数据请求接口
    public function user()
    {
        $data = Db::name('form')->order('id','desc')->paginate('10');
        $list = $data->toArray();
        return json(["code"=>0,"msg"=>"", "count"=>$list['total'] ,"data"=>$list['data']]);
    }

    // 邮箱验证
    public function send_mail()
    {
        $email = input('post.email');
        $user = Db::query("select `nickname` from `think_user` where `email` =" ." '$email' "."limit 1");
        //dump($user);die;
        if($user[0]['user_name'] != input('session.user_name')){
            return 404;
        }
        $mail = new UserModel();
        $toemail = input('post.email');
        $name = 'yxl';
        $subject = 'yxl 测试员修改密码';
        $data = rand(1000, 9999);
        $content = '您的验证码为';
        if(send_mail($mail,$toemail, $name, $subject, $content.$data) == true){
            session('note',$data);
            return json(['code' => 1, 'data' => $mail, 'msg' => 'ok']);
        }else{
            return json(['code' => 1, 'msg' => '验证失败']);
        }
    }

    // 手机号验证
    public function send_sms(){

        $phone = input('post.phone');
        $phonemodel = new UserModel();
        $time = $phonemodel->get(array('phone'=>$phone));
        if ($time != true) {
            return 404;
        }
        $send = time();
        if($send - $time->sendtime > 3600*24){
            $time->num = 0;
            $nn = $time->save();
            if(!$nn){
                return false;
            }
        }

        if ($send - $time->sendtime  < 180 || $time->num  >= 5 ) {
            return 100;
        }
        $serverIP = config("sms.serverIP");
        $serverPort = config("sms.serverPort");
        $softVersion = config("sms.softVersion");
        $rest = new Rest($serverIP, $serverPort, $softVersion);
        //Demo调用,参数填入正确后，放开注释可以调用
        $time->sendtime = $send;
        $newtime = $time->save();
        $data = array(rand(1000, 9999), 2);
        if ((sendTemplateSMS($rest, $phone, $data, "240793" && $newtime) == true)) {
            session('phonecode', $data[0]);
            $time->num = $time->num+1;
            $u = $time->save();
            if(!$u){
                return json(['code' => 1, 'msg' => '验证失败']);
            }
            return json(['code' => 1, 'data' => $u, 'msg' => 'ok']);
        } else {
            return json(['code' => 1, 'msg' => '手机号验证失败']);
        }
    }

    //验证码登录
    public function doSmsLogin(){
        //$name = input('post.title');
        $phone = input('post.phone');
        $captcha = input('post.code');
        $smscaptcha = input('session.smscaptcha');
        if($smscaptcha == $captcha){
            session('phone',$phone);
            return json(['code' => 1, 'data' => $smscaptcha, 'msg' => 'ok']);
        }else{
            return json(['code' => 2,  'msg' => '失败']);
        }
    }

    // 渲染添加
    public function add()
    {
        return $this->fetch();
    }

    // 处理添加
    public function add_do()
    {
        //入库之前进行数据验证
        $data = input();
        $data['password'] = md5($data['password']);
        $data['like'] = implode(',', array_keys($data['like']));
        $model = new UserModel();
        $res = $model->allowField(true)->save($data);
        if (!$res) {
            return $res->getError();
        } else {
            return json(['code' => 1, 'data' => $res, 'msg' => 'ok']);
        }
    }

    // 删除操作
    public function del()
    {
        $data = input('post.');
        $id = $data['id'];
        $res = UserModel::destroy($id);
        if($res)
        {
            return json(['code' => 1, 'data' => $res, 'msg' => 'ok']);
        }else
        {
            return $res->getError();
        }
    }

    // 批删操作
    public function delAll()
    {
        $id = rtrim(input('post.id'),',');
        // rtrim — 删除字符串末端的空白字符（或者其他字符）
        $result = Db::execute("delete from think_form where id in ($id) ");
        if ($result) {
            return json(['code' => 1, 'data' => $result, 'msg' => 'ok']);
        } else {
            return $result->getError();
        }
    }

    // 渲染修改
    public function update()
    {
        $id = input('get.');
        $user = UserModel::find($id);
        $this->assign('list',$user);
        return $this->fetch();
    }

    // 修改处理
    public function doUpdate()
    {
        $data = input();
        $id = $data['id'];
        $data['like'] = implode(',',array_keys($data['like']));
        $data['password'] = md5($data['password']) ;
        $blog = new UserModel();
        if ($blog->update(['id'=>$id])->save($data)) {
            return json(['code' => 1, 'data' => $blog, 'msg' => 'ok']);
        } else {
            return $blog->getError();
        }
    }

    // 渲染文件
    public function upload()
    {
        $user = Session::get("user_name");
        $this->assign('user',$user);
        return view();
    }

    // 处理文件上传
    public function uploadLayui(Request $request)
    {
        if ( $request->isAjax() )
        {
            $file = $request->file('file');
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if ($info)
            {
                $res['code'] = 1;
                $res['savename'] = "/uploads/".$info->getSaveName();
            } else{
                $res['code'] = 0;
                $res['err'] = $info->getError();
            }
            $model = new UserModel();
            $model->allowfield(true)->save(['file'=>$res['savename']]);
            return json($res);
        }
    }

    // 即点即改
    public function littleUpdate()
    {
        $id = input('post.id');
        $field = input('post.y');
        $value = input('post.x');
        $res = UserModel::get($id);
        $res->$field = $value;
        $data = $res->save();
        if($data)
        {
            return json(['code' => 1, 'data' => $data, 'msg' => 'ok']);
        }else
        {
            return json(['code' => 2,'msg' => '修改失败']);
        }
    }

    //图片轮播
    public function img(){

        $data = Db ::name('img')->where('is_visible',1)->order('sort','asc')->limit(5)->select();
        $this->assign('row',$data);
        return view();
    }

    //流加载
    public function flow(){
        $flow = Db ::name('img')->where('is_visible',1)->limit(5)->select();
        $this->assign('flow',$flow);
        return view();
    }

    // 渲染手机号验证页面
    public function phone()
    {
        return $this->fetch();
    }
}
